package com.rongshu.view.userInfo.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.userInfo.adapter.VipImgAuthenticationAdapter;
import com.rongshu.view.userInfo.entity.PostVipAuthentication;
import com.rongshu.view.userInfo.entity.UpLoadImage;
import com.rongshu.view.userInfo.entity.VipImgAuthentication;
import com.rongshu.view.userInfo.iview.AddProductionView;
import com.rongshu.view.userInfo.listener.OnVipImgFunctionClickListener;
import com.rongshu.view.userInfo.presenter.AddProductionPresenter;
import com.widget.EditTextWithDel;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class AddProductionActivity extends BaseActivity<AddProductionPresenter> implements AddProductionView, OnVipImgFunctionClickListener {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.txt_top_function)
    TextView txt_top_function;
    @BindView(R.id.txt_name)
    TextView txt_name;
    @BindView(R.id.edt_name)
    EditTextWithDel edt_name;
    @BindView(R.id.line_name)
    View line_name;
    @BindView(R.id.txt_platform)
    TextView txt_platform;
    @BindView(R.id.edt_platform)
    EditTextWithDel edt_platform;
    @BindView(R.id.line_platform)
    View line_platform;
    @BindView(R.id.txt_upload)
    TextView txt_upload;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    //intent
    private Intent intent = null;
    //type
    private int type = -1;
    //hint name
    private String name = null;
    //hint platform
    private String platform = null;
    //bean
    private PostVipAuthentication.VipDateModeBean bean = null;
    //adapter
    private VipImgAuthenticationAdapter adapter = null;
    //list
    private List<VipImgAuthentication> list = null;
    //type
    private int imgType = 0;
    //position
    private int position = 0;
    //boolean
    private boolean isModification = false;
    //dataImg
    private String dataImg = null;

    @Override
    protected int initLayout() {
        return R.layout.activity_add_production_view;
    }

    //1.已发表作品，2.纸媒发表作品，3.新媒体平台作品，4.获奖情况，5.其他平台加V认证ID
    @Override
    protected void initView() {
        //presenter
        setPresenter(new AddProductionPresenter(this), this);
        intent = getIntent();
        if (intent == null) {
            return;
        }
        type = intent.getIntExtra(Constant.INTENT_TYPE, -1);
        name = intent.getStringExtra(Constant.INTENT_TITLE);
        bean = (PostVipAuthentication.VipDateModeBean) intent.getSerializableExtra(Constant.INTENT_DATA);
        if (type == 1 || type == 2 || type == 3 || type == 5) {
            platform = intent.getStringExtra(Constant.INTENT_MESSAGE);
        }
        //title
        txt_top_title.setText(
                type == 1 ? "添加ISBN" :
                        type == 2 ? "添加作品" :
                                type == 3 ? "添加作品" :
                                        type == 4 ? "添加奖项" :
                                                type == 5 ? "添加ID" : "");
        txt_name.setText(name);
        //edt_name
        if (bean != null) {
            isModification = true;
            edt_name.setText(bean.getDataName());
        }
        edt_name.setSelection(edt_name.getText().toString().length());
        //function
        txt_top_function.setText("确定");
        if (type == 1 || type == 2 || type == 3 || type == 5) {
            txt_platform.setText(platform);
            txt_platform.setVisibility(View.VISIBLE);
            edt_platform.setVisibility(View.VISIBLE);
            line_platform.setVisibility(View.VISIBLE);
        } else {
            txt_platform.setVisibility(View.GONE);
            edt_platform.setVisibility(View.GONE);
            line_platform.setVisibility(View.GONE);
        }
        //edt_platform
        if (bean != null) {
            edt_platform.setText(bean.getDataRemarks());
        }
        //upload
        txt_upload.setVisibility(type == 5 ? View.VISIBLE : View.GONE);
        recyclerView.setVisibility(type == 5 ? View.VISIBLE : View.GONE);
        if (type == 5) {
            //list
            list = new ArrayList<>();
            if (bean != null) {
                dataImg = bean.getDataImg();
                if (TextUtils.isEmpty(dataImg)) {
                    list.add(new VipImgAuthentication());
                } else {
                    list.add(new VipImgAuthentication(dataImg, 1));
                }
            } else {
                list.add(new VipImgAuthentication());
            }
            //adapter
            adapter = new VipImgAuthenticationAdapter(this);
            adapter.setOnVipImgFunctionClickListener(this);
            adapter.setVipImgAuthenticationList(list);
            //manager
            LinearLayoutManager manager = new LinearLayoutManager(this,
                    LinearLayoutManager.HORIZONTAL, false);
            //recyclerview
            recyclerView.setLayoutManager(manager);
            recyclerView.setAdapter(adapter);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }


    /**
     * 上传的图片集合
     */
    private void uploadImages() {
        Map<String, RequestBody> bodyMap = new HashMap<>();
        List<VipImgAuthentication> uploadList = adapter.getVipImgAuthenticationListForType(1);
        if (!uploadList.isEmpty()) {
            for (int i = 0; i < uploadList.size(); i++) {
                File file = new File(uploadList.get(i).getVipImgPath());
                bodyMap.put("file" + i + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
            }
            presenter.postUploadMoreFile(bodyMap);
        } else {
            toast("请上传图片");
        }
    }

    @OnClick({R.id.layout_back, R.id.txt_top_function})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                showKeyboard(false);
                finish();
                break;
            case R.id.txt_top_function://确定
                getVipAuthenticationMsg();
                if (bean == null) {
                    return;
                }
                if (type != 5 || isModification) {
                    intent = new Intent();
                    if (isModification) {
                        if (type == 5) {
                            bean.setDataImg(dataImg);
                        }
                    }
                    intent.putExtra(Constant.INTENT_DATA, bean);
                    setResult(RESULT_OK, intent);
                    showKeyboard(false);
                    finish();
                } else {
                    uploadImages();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://相册返回
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    String path = selectList.get(0).getPath();
                    if (list == null) {
                        return;
                    }
                    if (imgType == 0) {
                        list = adapter.getVipImgAuthenticationListForType(1);
                        list.add(new VipImgAuthentication(path, 1));
                        if (list.size() < 1) {
                            list.add(new VipImgAuthentication());
                        }
                    } else {
                        list.set(position, new VipImgAuthentication(path, 1));
                    }
                    isModification = false;
                    adapter.setVipImgAuthenticationList(list);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     * 获取vip认证信息
     */
    public void getVipAuthenticationMsg() {
        bean = null;
        int vipType = 0;
        String dataName = null;
        String dataRemarks = null;
        switch (type) {
            case 1://已出版作品
                vipType = 1;
                dataName = edt_name.getText().toString().trim();
                dataRemarks = edt_platform.getText().toString().trim();
                if (TextUtils.isEmpty(dataName)) {
                    toast("请输入作品名称");
                    return;
                }
                if (TextUtils.isEmpty(dataRemarks)) {
                    toast("请输入ISBN号");
                    return;
                }
                break;
            case 2://纸媒发表作品
                vipType = 2;
                dataName = edt_name.getText().toString().trim();
                dataRemarks = edt_platform.getText().toString().trim();
                if (TextUtils.isEmpty(dataName)) {
                    toast("请输入作品名称");
                    return;
                }
                if (TextUtils.isEmpty(dataRemarks)) {
                    toast("请输入发表刊物名称");
                    return;
                }
                break;
            case 3://新媒体平台作品
                vipType = 3;
                dataName = edt_name.getText().toString().trim();
                dataRemarks = edt_platform.getText().toString().trim();
                if (TextUtils.isEmpty(dataName)) {
                    toast("请输入作品名称");
                    return;
                }
                if (TextUtils.isEmpty(dataRemarks)) {
                    toast("请输入新媒体平台名称");
                    return;
                }
                break;
            case 4://获奖情况
                vipType = 4;
                dataName = edt_name.getText().toString().trim();
                if (TextUtils.isEmpty(dataName)) {
                    toast("请输入奖项");
                    return;
                }
                break;
            case 5://其他平台加v认证id
                vipType = 5;
                dataName = edt_name.getText().toString().trim();
                dataRemarks = edt_platform.getText().toString().trim();
                if (TextUtils.isEmpty(dataName)) {
                    toast("请输入加V ID");
                    return;
                }
                if (TextUtils.isEmpty(dataRemarks)) {
                    toast("请输入平台名称");
                    return;
                }
                break;
        }
        bean = new PostVipAuthentication.VipDateModeBean();
        bean.setType(vipType);
        bean.setDataName(dataName);
        bean.setDataRemarks(dataRemarks);
    }

    /**
     * item click
     *
     * @param type
     * @param position
     */
    @Override
    public void onItemClick(int type, int position) {
        this.imgType = type;
        this.position = position;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 图片上传返回
     *
     * @param upLoadImage
     */
    @Override
    public void uploadImageResult(UpLoadImage upLoadImage) {
        StringBuffer dataImg = new StringBuffer();
        if (upLoadImage.getErrCode() == 0) {
            List<String> imgList = upLoadImage.getResponse().getImgUrl();
            if (imgList == null) {
                return;
            }
            for (int i = 0; i < imgList.size(); i++) {
                dataImg.append(imgList.get(i));
                if (i != imgList.size() - 1) {
                    dataImg.append("|");
                }
            }

            if (bean == null) {
                return;
            }
            bean.setDataImg(dataImg.toString());
            intent = new Intent();
            intent.putExtra(Constant.INTENT_DATA, bean);
            setResult(RESULT_OK, intent);
            showKeyboard(false);
            finish();
        } else {
            toast(upLoadImage.getErrMsg());
        }
    }
}
